//
//  Crop.h
//  Bespoke
//
//  Created by Rafale Chang on 12/7/28.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//



#import "Crop.h"

@implementation UIImage (Crop)

- (UIImage *)crop:(CGRect)rect {
    
    CGFloat scale = [[UIScreen mainScreen] scale];
    
    if (scale>1.0) {        
        rect = CGRectMake(rect.origin.x*scale , rect.origin.y*scale, rect.size.width*scale, rect.size.height*scale);        
    }
    
    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef);
    return result;
}

- (UIImage *)resize:(CGSize)newsize
{
    UIGraphicsBeginImageContext( newsize );
    [self drawInRect:CGRectMake(0,0,newsize.width,newsize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}



#pragma mark -
#pragma mark Scale and crop image

- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
UIImage *sourceImage = self;
UIImage *newImage = nil;        
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (CGSizeEqualToSize(imageSize, targetSize) == NO) 
{
    CGFloat widthFactor = targetWidth / width;
    CGFloat heightFactor = targetHeight / height;
    
    if (widthFactor > heightFactor) 
        scaleFactor = widthFactor; // scale to fit height
    else
        scaleFactor = heightFactor; // scale to fit width
    scaledWidth  = width * scaleFactor;
    scaledHeight = height * scaleFactor;
    
    // center the image
    if (widthFactor > heightFactor)
    {
        thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
    }
    else 
        if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
}       

UIGraphicsBeginImageContext(targetSize); // this will crop

CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width  = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil) 
NSLog(@"could not scale image");

//pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}

#pragma mark - 
#pragma mark SetImageSize

- (UIImage *)SetImageSize:(int)FrameWidth Height:(int)FrameHeight {
    
    UIImage *OriginalImage = self;
    float Scale;
    CGSize itemSize;
    CGRect imageRect;
    
    if (OriginalImage.size.width>FrameWidth) {
        
        Scale = FrameWidth/OriginalImage.size.width;
        
        itemSize = CGSizeMake(FrameWidth, OriginalImage.size.height*Scale);
        UIGraphicsBeginImageContext(itemSize);
        imageRect = CGRectMake(0, 0, FrameWidth, OriginalImage.size.height*Scale);
        [OriginalImage drawInRect:imageRect];
        OriginalImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    if (OriginalImage.size.height>FrameHeight) {
        
        Scale = FrameHeight/OriginalImage.size.height;
        
        itemSize = CGSizeMake(OriginalImage.size.width*Scale, FrameHeight);
        UIGraphicsBeginImageContext(itemSize);
        imageRect = CGRectMake(0, 0, OriginalImage.size.width*Scale, FrameHeight);
        [OriginalImage drawInRect:imageRect];
        OriginalImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return OriginalImage;
}

#pragma mark - 
#pragma mark Check image orientation. Fixed upside down.

- (UIImage *)fixOrientation {
    
    UIImage *Photo = self;
    
    // No-op if the orientation is already correct
    if (Photo.imageOrientation == UIImageOrientationUp)
        return Photo;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (Photo.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, Photo.size.width, Photo.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, Photo.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, Photo.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (Photo.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, Photo.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, Photo.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, Photo.size.width, Photo.size.height,
                                             CGImageGetBitsPerComponent(Photo.CGImage), 0,
                                             CGImageGetColorSpace(Photo.CGImage),
                                             CGImageGetBitmapInfo(Photo.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (Photo.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,Photo.size.height,Photo.size.width), Photo.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,Photo.size.width,Photo.size.height), Photo.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

@end